package com.xcc.core.netty.client;

import com.xcc.core.netty.NettyClient;
import com.xcc.core.netty.NettyRealClient;
import com.xcc.core.netty.manager.ManagerChannel;
import com.xcc.core.util.ZkClientUitl;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

//mysql 映射端通信
public class RealChannelHandler extends ChannelInboundHandlerAdapter{

    ClientUtil mClientUtil=new ClientUtil();
    //激活mysql 服务端channel
    @Override
    public void channelActive(ChannelHandlerContext ctx)
        throws Exception {
        ManagerChannel.putSeverChannel(ctx.channel());
   //     ZkClientUitl.createEphemeral("/server/"+ctx.channel().id().asLongText(),"".getBytes());
        //启动连接代理服务器
        new NettyClient("127.0.0.1",10087).start();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)
        throws Exception {
        for(String key:ManagerChannel.getAllServer().keySet()) {
            if(!key.equals(ctx.channel().id().asLongText())) {
                    mClientUtil.write(key,(ByteBuf)msg );
            }
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
        throws Exception {
        System.out.println("real 连接异常");
        ManagerChannel.removeClient(ctx.channel());
        new NettyRealClient("127.0.0.1",3389).start();
        super.exceptionCaught(ctx, cause);
      
    }

}
